// IBatisBaseDao
package org.yate.oa.dao;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.yate.oa.utils.Pagination;
import org.yate.oa.utils.ReflectionUtils;

/**
 * @author Yate
 * @date 2013年9月23日
 * @description TODO
 * @version 1.0
 */
public abstract class IBatisBaseDao<E, PK> implements IBaseDao<E, PK> {
	@Resource(name = "sqlSession")
	protected SqlSession sqlSession;

	protected Class<E> entityClass;

	@SuppressWarnings("unchecked")
	public IBatisBaseDao() {
		this.entityClass = (Class<E>) ReflectionUtils
				.getSuperClassGenricType(this.getClass());
	}

	@Override
	public final void add(E e) throws Exception {
		if (e != null) {
			this.sqlSession.insert(e.getClass().getName() + ".add", e);
		} else
			throw new Exception("add paramter is null!");
	}

	@Override
	public final void remove(E e) throws Exception {
		if (e != null) {
			sqlSession.delete(e.getClass().getName() + ".remove", e);
		} else
			throw new Exception("remove paramter is null!");
	}

	@Override
	public final void update(E e) throws Exception {
		if (e != null) {
			sqlSession.update(e.getClass().getName() + ".update", e);
		} else
			throw new Exception("update paramter is null!");
	}

	@Override
	public Pagination<E> getEntities(Pagination<E> page) throws Exception {
		throw new UnsupportedOperationException("unsupported");
	}

	@Override
	public E getEntity(PK id) throws Exception {
		return sqlSession.selectOne(this.entityClass.getName() + ".get", id);
	}

	/**
	 * @return the sqlSession
	 */
	public final SqlSession getSqlSession() {
		return sqlSession;
	}

}
